package cn.wolfcode.p2p.util;

import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.vo.UserInfoVo;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 上下文工具类
 */
public abstract class UserContext {
    public static final String USER_IN_SESSSION = "USER_IN_SESSSION";
    public static final String LOGININFO_IN_SESSION = "logininfo";

    /**
     * 将用户的信息保存到session中
     * @param userInfoVo 存储用户信息
     */
    public static void setUserInfoVo(UserInfoVo userInfoVo){
        getSession().setAttribute(USER_IN_SESSSION,userInfoVo);
    }

    /**
     * 将用户的登陆信息保存到session中
     * @param loginInfo 登陆信息
     */
    public static void setLoginInfo(LoginInfo loginInfo){
        getSession().setAttribute(LOGININFO_IN_SESSION,loginInfo);
    }

    /**
     *获取session对象
     * @return sesssion
     */
    public static UserInfoVo getUserInfoVo(){
        return (UserInfoVo) getSession().getAttribute(USER_IN_SESSSION);

    }
    /**
     *获取session中的loginInfo对象
     * @return sesssion
     */
    public static LoginInfo getLoginInfo(){
        return (LoginInfo) getSession().getAttribute(LOGININFO_IN_SESSION);

    }

    /**
     * 获取ip
     */
    public static String getIp(){
        return getRequest().getRemoteAddr();
    }

    /**
     *  从session中获取session对象
     * @return
     */
    public  static HttpSession getSession(){
        return getRequest().getSession();
    }

    /**
     * 获取request对象
     */
    public static HttpServletRequest getRequest(){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getRequest();
    }

}
